<?php

namespace app\common\model\biz;


use app\common\model\BaseModel;

class SysMenu extends BaseModel
{

    public static function tree(array $menus, int $pid = 0, bool $all = true): array
    {
        $data = [];
        foreach ($menus as $k => $menu) {
            if (!$all && 3 === $menu['type']) {
                //按钮
                continue;
            }

            $menu['value'] = $menu['id'];
            $menu['label'] = $menu['name'];

            if ($pid === $menu['pid']) {

                $row = $menu;
                unset($menus[$k]);

                $children = self::tree($menus, $menu['id'], $all);
                if (!empty($children)) {
                    $row['children'] = $children;
                }

                $data[] = $row;
            }
        }

        return $data;
    }

    public static function treeByChildren(array $menus, array $ids): array
    {
        $data = [];
        foreach ($menus as $k => $menu) {
            $menu['value'] = $menu['id'];
            $menu['label'] = $menu['name'];

            if (in_array($menu['id'], $ids)) {

                $data[$menu['id']] = $menu;
                if (!empty($menu['pid'])) {
                    unset($menus[$k]);
                    $row = self::treeByChildren($menus, [$menu['pid']]);
                    if (!empty($row)) {
                        foreach ($row as $item) {
                            $data[$item['id']] = $item;
                        }
                    }
                }
            }
        }

        return $data;
    }

    public static function sort(array &$menus): void
    {
        foreach ($menus as &$menu) {
            if (!empty($menu['children'])) {
                self::sort($menu['children']);
            }
        }

        usort($menus, function ($v1, $v2) {
            return $v1['sort'] === $v2['sort'] ? 0 : ($v1['sort'] < $v2['sort'] ? -1 : 1);
        });
    }
}